# -*- coding: utf-8 -*-

'''eof
name:最近一年订烟活跃月份数占比（LT）
code:Mon12ActiveOrder_LT
tableName:
columnName:
groups:烟商
dependencies:BTM
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
"1.计算申请日期前每个30天的订单次数：
（1）统计申请日期前第i * 30 +1天 ~ (i + 1) * 30天的订单次数记作申请前第(i+1)月的订单次数，i0 = 0，do i = i +1 ,until(申请日期 - (i + 1) *30)≤最小订单日期 then stop；
（2）分子 = Count 步骤1中月订单次数 ＞ 2 的条数
2.分母 = Roundup（申请日期 - 最小订单日期 + 1）/30
3.指标值 = 分子/分母"
'''

import sys
import pandas as pd
import datetime
import re
import math

reload(sys)
sys.setdefaultencoding('utf-8')


def Mon12ActiveOrder_LT():
    null_type_list = ['', None, 'null', 'Null', '/', ' ']
    count = {'T12': [], 'T11': [], 'T10': [], 'T9': [], 'T8': [], 'T7': [], 'T6': [], 'T5': [],
             'T4': [], 'T3': [], 'T2': [], 'T1': []}
    count_num = []
    indent_date = []


    try:
        BTM_ = BTM['data']
        if BTM_.has_key('bbd_dotime') and Formate(BTM_['bbd_dotime']) not in null_type_list:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_months_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
            for i in xrange(12, -1, -1)]
        else:
            last_year_months_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                                     for i in xrange(12, -1, -1)]
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
                and len(BTM_['indent']) >= 1:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                        and Formate(i['indentDate']) is not None \
                        and i.has_key('indentNum') and i['indentNum'] not in null_type_list \
                        and Formate(i['indentDate']) > last_year_months_list[0] and Formate(i['indentDate']) <= \
                        last_year_months_list[-1]:
                    indent_date.append(Formate(i['indentDate']))
                    if Formate(i['indentDate']) > last_year_months_list[0] and Formate(i['indentDate']) <= \
                            last_year_months_list[1]:
                        count['T12'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[1] and Formate(i['indentDate']) <= \
                            last_year_months_list[2]:
                        count['T11'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[2] and Formate(i['indentDate']) <= \
                            last_year_months_list[3]:
                        count['T10'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[3] and Formate(i['indentDate']) <= \
                            last_year_months_list[4]:
                        count['T9'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[4] and Formate(i['indentDate']) <= \
                            last_year_months_list[5]:
                        count['T8'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[5] and Formate(i['indentDate']) <= \
                            last_year_months_list[6]:
                        count['T7'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[6] and Formate(i['indentDate']) <= \
                            last_year_months_list[7]:
                        count['T6'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[7] and Formate(i['indentDate']) <= \
                            last_year_months_list[8]:
                        count['T5'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[8] and Formate(i['indentDate']) <= \
                            last_year_months_list[9]:
                        count['T4'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[9] and Formate(i['indentDate']) <= \
                            last_year_months_list[10]:
                        count['T3'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[10] and Formate(i['indentDate']) <= \
                            last_year_months_list[11]:
                        count['T2'].append(i['indentNum'])
                    elif Formate(i['indentDate']) > last_year_months_list[11] and Formate(i['indentDate']) <= \
                            last_year_months_list[12]:
                        count['T1'].append(i['indentNum'])
                    else:
                        pass
            for k in count.keys():
                if count[k] != []:
                    count_num.append(len(count[k]))
            active_num = len([i for i in count_num if i > 2.0])
            month_num = ((ApplTime- datetime.datetime.strptime(min(indent_date), '%Y%m%d')).days + 1) / float(30)
            if month_num != 0:
                return round(float(active_num) / float(math.ceil(month_num)), 4)
            else:
                print 1
                return u'缺失值'
        else:
            print 2
            return u'缺失值'
    except:
        return u'缺失值'


# 统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


result = Mon12ActiveOrder_LT()